package 共享锁实现.javaapilock;

import lombok.Data;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import 操作zookeeper.javaAPI.APIdemo;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * author Veng Su
 * email  1344114844@qq.com
 * date   18-9-17 上午10:21
 */
@Data
public class ZkClient {
    public final static String CONNECTSTRING = "192.168.0.201:2181,192.168.0.203:2181,192.168.0.204:2181";
    public static ZooKeeper zooKeeper;//zookeeper对象
    public static Stat stat = new Stat();//不给的全局，状态会话会丢失，导致执行失败
    private static int sessionTimeout=5000;
    public static CountDownLatch countDownLatch = new CountDownLatch(1);//计数器用于同步连接


    public static ZooKeeper getInstance() throws IOException, InterruptedException {

        ZooKeeper zooKeeper =new ZooKeeper(CONNECTSTRING, sessionTimeout, watchedEvent -> {
            if (watchedEvent.getState() == Watcher.Event.KeeperState.SyncConnected) {
                countDownLatch.countDown();
            }

        });
        countDownLatch.await();
        return zooKeeper;

    }
    public static int getSessionTimeout(){
        return sessionTimeout;
    }



}
